package com.kalman.biz.common;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.core.io.ResourceLoader;

/**
 * @author kalman03
 */
public class HnrResourceLoader{
	
	
	public static String getResoureceAsString(String fileName) throws IOException {
		InputStream inputStream = null;
		try {
			inputStream = getResoureceAsInputStream(fileName);
			int count = 0;
			while (count == 0) {
				count = inputStream.available();
			}
			byte[] b = new byte[count];
			inputStream.read(b);
			return new String(b);
		}finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}
	}
	
	public static byte[] getResoureceAsByteArray(String fileName) throws IOException {
		InputStream inStream = getResoureceAsInputStream(fileName);
		ByteArrayOutputStream arrayOutputStream = null;
		try {
			arrayOutputStream = new ByteArrayOutputStream();
			byte[] buff = new byte[100];
			int rc = 0;
			while ((rc = inStream.read(buff, 0, 100)) > 0) {
				arrayOutputStream.write(buff, 0, rc);
			}
			return arrayOutputStream.toByteArray();
		}finally{
			if(arrayOutputStream != null)arrayOutputStream.close();
			if(inStream != null)inStream.close();
		}
	}
	
	public static InputStream getResoureceAsInputStream(String fileName) throws IOException {
		checkArgument(!isNullOrEmpty(fileName),"filename is required.");
		return ResourceLoader.class.getClassLoader().getResourceAsStream(fileName);
	}
	
	
}
